package de.tum.in.eist.poll.adapter;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.visualization.client.AbstractDataTable;
import com.google.gwt.visualization.client.AbstractDataTable.ColumnType;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.google.gwt.visualization.client.visualizations.ImagePieChart;

import de.tum.in.eist.poll.controller.FeedbackController;
import de.tum.in.eist.poll.controller.LectureController;
import de.tum.in.eist.poll.service.OnDataUpdate;
import de.tum.in.eist.poll.shared.Feedback;
import de.tum.in.eist.poll.shared.Student;

/**
 * Used to display a lecture
 * 
 * @author sudi
 * 
 */
public class LectureAdapter {

	LectureController lectureController;
	FeedbackController feedbackController;

	String satisfactions[];

	FlexTable feedback;
	HorizontalPanel statistics;
	Label randomLike = new Label();
	Label randomDislike = new Label();
	Button rateButton;

	List<Feedback> feedbackList;

	public LectureAdapter(LectureController lC,
			FeedbackController feedbackController) {
		lectureController = lC;
		this.feedbackController = feedbackController;
		satisfactions = new String[5];
		satisfactions[0] = "Very unsatisfied";
		satisfactions[1] = "Unsatisfied";
		satisfactions[2] = "Neutral";
		satisfactions[3] = "Satisfied";
		satisfactions[4] = "Very Satisfied";
	}

	/**
	 * add feedback to the lecture view
	 * 
	 * @param idx
	 *            Index of the feedback
	 * @param sf
	 *            The feedback
	 */
	public void addFeedback(int idx, Feedback sf) {
		feedback.setText(idx, 0, satisfactions[sf.getSatisfaction()]);
		feedback.setText(idx, 1, sf.getLike());
		feedback.setText(idx, 2, sf.getDisLike());
		if (sf.getSatisfaction() < 2) {
			feedback.getRowFormatter().addStyleName(idx, "negativeFeedback");
		} else if (sf.getSatisfaction() > 2) {
			feedback.getRowFormatter().addStyleName(idx, "positiveFeedback");
		} else if (sf.getSatisfaction() == 2) {
			feedback.getRowFormatter().addStyleName(idx, "neutralFeedback");
		}
	}

	/**
	 * Create PieChart options
	 * 
	 * @return the PieChart Options
	 */
	private ImagePieChart.Options createOptions() {
		ImagePieChart.Options options = ImagePieChart.Options.create();
		options.setWidth(400);
		options.setHeight(240);
		options.setTitle("Feedback");
		options.setLabels("value");
		options.setBackgroundColor("#00000000");
		String[] colors = { "#FF0000", "#FF8000", "#2B60DE", "#74DF00",
				"#04B404" };
		options.setColors(colors);
		options.setTitleColor("#000000");
		options.setTitleFontSize(30);
		return options;
	}

	/**
	 * Count the feedback with specific satisfaction
	 * 
	 * @param value
	 *            satisfaction
	 * @return count of Feedback with this satisfaction
	 */
	private int countFor(int value) {
		Iterator<Feedback> it = feedbackList.iterator();
		int count = 0;
		while (it.hasNext()) {
			Feedback f = it.next();
			Feedback sf = f;
			if (sf.getSatisfaction() == value)
				count++;
		}
		return count;
	}

	/**
	 * create datatable of piechart
	 * 
	 * @return the datatable
	 */
	private AbstractDataTable createTable() {
		DataTable data = DataTable.create();
		data.addColumn(ColumnType.STRING, "Satisfaction");
		data.addColumn(ColumnType.NUMBER, "Rating");
		data.addRows(5);
		for (int row = 0; row < 5; row++) {
			data.setValue(row, 0, satisfactions[row]);
			data.setValue(row, 1, countFor(row));
		}
		return data;
	}

	/**
	 * create the lecture view
	 */
	public void create() {
		RootPanel.get().add(
				new HTML("<h1>"
						+ lectureController.getSelected().getLectureTitle()
						+ "</h1>"));
		// add rate button when needed
		if (lectureController.getUserController().getUser() instanceof Student
				&& !lectureController.getSelected().containsStudent(
						(Student) lectureController.getUserController()
								.getUser())) {
			rateButton = new Button("Rate");
			rateButton.addClickHandler(new ClickHandler() {

				@Override
				public void onClick(ClickEvent event) {
					// !TODO maybe change this not sure
					History.newItem("feedback");
				}

			});
			RootPanel.get().add(rateButton);
		}

		// add diagramm and random message
		statistics = new HorizontalPanel();
		statistics.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		statistics.setStyleName("statistic_rand");
		statistics.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		RootPanel.get().add(statistics);

		VerticalPanel randomStuff = new VerticalPanel();
		randomStuff.add(randomLike);
		randomStuff.add(randomDislike);
		randomStuff.setStyleName("statistic_rand");
		statistics.add(randomStuff);

		// add table with everything
		feedback = new FlexTable();
		feedback.setWidget(0, 0, new HTML("<h2><u>Satisfaction</u></h2>"));
		feedback.setWidget(0, 1, new HTML("<h2><u>Like</u></h2>"));
		feedback.setWidget(0, 2, new HTML("<h2><u>Dislike</u></h2>"));
		feedback.setStyleName("statistic");

		RootPanel.get().add(feedback);

		feedbackController.fetchFeedback(new OnDataUpdate<List<Feedback>>() {

			@Override
			public void onDataUpdate(List<Feedback> data) {

				if (data != null)
					feedbackList = data;
				else
					feedbackList = new LinkedList<Feedback>();

				Runnable onLoadCallback = new Runnable() {
					public void run() {
						// Create a pie chart visualization.
						ImagePieChart pie = new ImagePieChart();
						pie.draw(createTable(), createOptions());

						// pie.addSelectHandler(createSelectHandler(pie));
						statistics.add(pie);
					}
				};

				VisualizationUtils.loadVisualizationApi(onLoadCallback,
						ImagePieChart.PACKAGE);

				Iterator<Feedback> it = feedbackList.iterator();
				int idx = 0;
				while (it.hasNext()) {
					idx++;
					Feedback f = it.next();

					addFeedback(idx, f);
				}
				if (!feedbackList.isEmpty()) {
					Feedback sf = feedbackList.get((int) (Math.random() * feedbackList
							.size()));
					randomLike.setText("Random Like: " + sf.getLike());
					randomDislike.setText("Random Dislike: " + sf.getDisLike());
				} else
					randomLike.setText("No Statistics yet");
			}

		});
	}
}
